<template>
  <div>
    <el-dialog :visible.sync="openModal" width="60%" :close-on-click-modal="false">
      <el-container>
        <el-header style="background: #fff;padding: 12px 12px;height:auto;">
          <div>
            <el-form :model="formData" label-position="right" label-width="120">
              <el-row :gutter="32">
                <el-col :span="12">
                  <el-form-item label="分区方案名称:" required>
                    <el-input v-model="formData.name" placeholder="分区方案名称" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-header>
        <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
          <div style="height: 100%;margin-bottom: 12px;display: flex;">
            <el-button type="primary" @click="add">添加分区</el-button>
          </div>
          <el-table :columns="table_header" :data="formData.specs" border>
            <el-table-column label="分区名称" min-width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="formData.specs[scope.$index].title" type="textarea" :rows="1" />
              </template>
            </el-table-column>
            <el-table-column label="目的地" min-width="100" align="center">
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.tags" type="border">{{ item }}</el-tag>
                <el-button type="primary" size="small" @click="addItem(scope.$index)">设置</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="del(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <div slot="footer">
        <el-button @click="openModal=false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="openModal2" width="60%" :close-on-click-modal="false">
      <el-row :gutter="32">
        <el-col :span="8">
          <el-card style="height: 540px;">
            <el-tabs v-model="tab" style="height: 500px;">
              <el-tab-pane label="国家" name="ST1">
                <el-select v-model="itemTemp.country" filterable multiple @change="countryChanged">
                  <el-option v-for="item in countrys" :key="item.code" :value="item.code" :label="item.nameCn" />
                </el-select>
              </el-tab-pane>
              <el-tab-pane label="亚马逊仓码" name="ST2">
                <el-select v-model="itemTemp.fbaCodes" filterable multiple placeholder="FBA仓码">
                  <el-option v-for="item in fbaAddressOption" :key="item.fbaCode" :value="item.fbaCode" :label="item.fbaCode" />
                </el-select>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
        <el-col v-show="tab === 'ST1'" :span="16">
          <el-card style="height: 540px;">
            <p slot="title">
              当选择国家时,可以设置邮编或者不设置
            </p>
            <el-table :columns="zipcode_header" :data="itemTemp.countryToZipcode" border :height="460">
              <el-table-column label="国家" align="center" prop="country" />
              <el-table-column label="邮编类型" align="center" min-width="100">
                <template slot-scope="scope">
                  <el-select v-model="itemTemp.countryToZipcode[scope.$index].zipcodeType" clearable filterable :transfer="true">
                    <el-option v-for="item in zipecodeType" :key="item.code" :value="item.code" :label="item.name" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="邮编" min-width="200" align="center">
                <template slot-scope="scope">
                  <div v-if="scope.row.zipcodeType === 'ZCT2'">
                    <el-row v-for="(item, index2) in itemTemp.countryToZipcode[scope.$index].zipcodes" :gutter="10">
                      <el-col :span="10">
                        <el-input v-model="itemTemp.countryToZipcode[scope.$index].zipcodes[index2].fromZipcode" placeholder="开始邮编" />
                      </el-col>
                      <el-col :span="10">
                        <el-input v-model="itemTemp.countryToZipcode[scope.$index].zipcodes[index2].toZipcode" placeholder="结束邮编" />
                      </el-col>
                      <el-col :span="4">
                        <el-button type="primary" ghost size="small" @click="delZipcodeItem(scope.$index,index2)">删除</el-button>
                      </el-col>
                    </el-row>
                    <el-row style="margin-top: 10px;">
                      <el-col :span="24">
                        <el-button type="primary" ghost size="small" @click="addZipcodeItem(scope.$index)">添加一行</el-button>
                      </el-col>
                    </el-row>
                  </div>
                  <el-input v-else v-model="itemTemp.countryToZipcode[scope.$index].fromZipcode" type="textarea" :rows="4" />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button @click="openModal2=false">取消</el-button>
        <el-button type="primary" @click="submitItem">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import request from '@/utils/request'
import { copyProperty } from '@/utils/tools'
export default {
  data() {
    return {
      tab: 'ST1',
      nameIndex: 1,
      openModal: false,
      openModal2: false,
      formDataDefault: {
        id: '',
        name: '',
        specs: []
      },
      formData: {
        id: '',
        name: '',
        specs: []
      },
      itemTemp: {
        country: [],
        fbaCodes: [],
        countryToZipcode: [],
        wh: [],
        countryToZipcodeMap: new Map(),
        parent: null
      },
      zipcode_header: [
        {
          title: '国家',
          align: 'center',
          key: 'country'
        },
        {
          title: '邮编类型',
          align: 'center',
          minWidth: 100,
          slot: 'zipcodeType'
        },
        {
          title: '邮编',
          minWidth: 200,
          align: 'center',
          slot: 'zipcode'
        }
      ],
      table_header: [
        {
          title: '分区名称',
          minWidth: 100,
          align: 'center',
          slot: 'title'
        },
        {
          title: '目的地',
          minWidth: 100,
          align: 'center',
          slot: 'items'
        },
        {
          title: '操作',
          minWidth: 100,
          align: 'center',
          slot: 'action'
        }
      ],
      codeToCountry: new Map(),
      zipecodeType: [
        {
          code: 'ZCT1',
          name: '以什么开头'
        },
        {
          code: 'ZCT2',
          name: '区间段'
        },
        {
          code: 'ZCT3',
          name: '完整邮编'
        }
      ],
      idToWarehouse: new Map()
    }
  },
  computed: {
    ...mapState(//
      {
        countrys: state => state.base.countrys,
        fbaAddressOption: state => state.base.fbaAddressOption
      }
    )
  },
  watch: {
    countrys() {
      this.countrys.forEach(e => {
        this.codeToCountry.set(e.code, e)
      })
    }
  },
  created() {
    if (this.countrys.length === 0) {
      this.$store.dispatch('getCountrys')
    } else {
      this.countrys.forEach(e => {
        this.codeToCountry.set(e.code, e)
      })
    }
    if (this.fbaAddressOption.length === 0) {
      this.$store.dispatch('getFbaAddress')
    }
  },
  methods: {
    submit() {
      if (!this.formData.name) {
        this.$message.error({
          message: '分区方案名称 必填',
          duration: 0,
          showClose: true
        })
        return
      }
      if (this.formData.specs.length === 0) {
         this.$message.error({
          message: '请添加分区',
          duration: 0,
          showClose: true
        })
        return
      }
      for (let index = 0; index < this.formData.specs.length; index++) {
        const spec = this.formData.specs[index]
        if (!spec.title) {
           this.$message.error({
            message: '分区名称 必填',
            duration: 0,
            showClose: true
          })
          return
        }
      }
      request({
        url: 'zone/add',
        data: this.formData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.openModal = false
          this.$emit('query')
        }
      })
    },
    delZipcodeItem(index, index2) {
      this.itemTemp.countryToZipcode[index].zipcodes.splice(index2, 1)
    },
    addZipcodeItem(index) {
      this.itemTemp.countryToZipcode[index].zipcodes.push({ fromZipcode: '', toZipcode: '' })
    },
    countryChanged(v) {
      const array = []
      v.forEach(e => {
        if (this.itemTemp.countryToZipcodeMap.has(e)) {
          array.push(this.itemTemp.countryToZipcodeMap.get(e))
        } else {
          const v = { country: e, zipcodes: [{ fromZipcode: '', toZipcode: '' }], fromZipcode: '', toZipcode: '', zipcodeType: '', countryName: this.codeToCountry.get(e).nameCn }
          this.itemTemp.countryToZipcodeMap.set(e, v)
          array.push(v)
        }
      })
      this.itemTemp.countryToZipcode = array
    },
    addItem(index) {
      this.cleanItemTemp()
      this.itemTemp.parent = index
      const row = this.formData.specs[index]
      if (row.tags.length > 0) {
        // 编辑
        copyProperty(this.itemTemp, row)
        row.countryToZipcode.forEach(e => {
          this.itemTemp.country.push(e.country)
          this.itemTemp.countryToZipcodeMap.set(e.country, e)
        })
        this.tab = row.type
      }
      this.openModal2 = true
    },
    submitItem() {
      let count = 0
     if (this.itemTemp.country.length > 0) {
      count++
      // 检查数据
      for (let index = 0; index < this.itemTemp.countryToZipcode.length; index++) {
        const e = this.itemTemp.countryToZipcode[index]
        if (e.zipcodeType) {
          if (e.zipcodeType === 'ZCT2') {
            for (let n = 0; n < e.zipcodes.length; n++) {
              const e2 = e.zipcodes[n]
              if (!e2.fromZipcode || !e2.toZipcode) {
                 this.$message.error({
                  message: '开始邮编 结束邮编必填',
                  duration: 0,
                  showClose: true
                })
                return
              }
            }
          } else if (!e.fromZipcode) {
             this.$message.error({
              message: '邮编必填',
              duration: 0,
              showClose: true
            })
            return
          }
        }
      }
     }
     if (this.itemTemp.fbaCodes.length > 0) {
      count++
     }
     if (this.itemTemp.wh.length > 0) {
      count++
     }
     if (count > 1) {
       this.$message.error({
        message: '只能设置其中一种方式',
        duration: 0,
        showClose: true
      })
      return
     }
     const row = this.formData.specs[this.itemTemp.parent]
     copyProperty(row, this.itemTemp)
     let tags = []
     if (this.itemTemp.fbaCodes.length > 0) {
      tags = this.itemTemp.fbaCodes
     } else if (this.itemTemp.countryToZipcode.length > 0) {
      this.itemTemp.countryToZipcode.forEach(e => {
        tags.push(this.codeToCountry.get(e.country).nameCn)
      })
     } else if (this.itemTemp.wh.length > 0) {
      this.itemTemp.wh.forEach(e => {
        tags.push(this.idToWarehouse.get(e).name)
      })
     }
     row.tags = tags
     row.type = this.tab
     this.cleanItemTemp()
     this.openModal2 = false
    },
    edit(data) {
      copyProperty(this.formData, data)
      this.formData.specs.forEach(e => {
        let tags = []
        if (e.fbaCodes.length > 0) {
          tags = e.fbaCodes
        } else if (e.countryToZipcode.length > 0) {
          e.countryToZipcode.forEach(e => {
            tags.push(this.codeToCountry.get(e.country).nameCn)
          })
        } else if (e.wh.length > 0) {
          e.wh.forEach(e => {
            tags.push(this.idToWarehouse.get(e).name)
          })
        }
        e.tags = tags
      })
      this.openModal = true
    },
    cleanItemTemp() {
      // 清理
      this.itemTemp.fbaCodes = []
      this.itemTemp.countryToZipcode = []
      this.itemTemp.wh = []
      this.itemTemp.country = []
      this.itemTemp.countryToZipcodeMap.clear()
      this.itemTemp.parent = null
    },
    add() {
      this.formData.specs.push({
        title: '分区' + (this.nameIndex++),
        fbaCodes: [],
        countryToZipcode: [],
        wh: [],
        tags: [],
        zoneType: ''
      })
    },
    del(index) {
      this.formData.specs.splice(index, 1)
    },
    show() {
      this.nameIndex = 1
      copyProperty(this.formData, this.formDataDefault)
      this.formData.id = ''
      this.openModal = true
    }
  }
}
</script>
